module GrapeAPI
  module BaseHelpers
    def response_format!(data = {})
      status 200
      data
    end

    def bad_request!
      error! "Bad Request", 400
    end

    def access_denied!
      error! "Access Denied", 401
    end

    def forbidden_request!
      error! "Forbidden", 403
    end

    def not_found!
      error! "Not Found", 404
    end
    
    def invalid_request!(message)
      error! message, 422
    end

    def unknow_user!
      error! "Unknow User", 432
    end

    def wrong_password!
      error! "Wrong Password", 433
    end

    def not_active!
      error! "UnActive User", 434
    end

    def already_have!
      error! "Already Have", 435
    end

    def token_expired!
      error! "Token expired", 436
    end
    
    def already_actived!
      error! "Already Actived", 437
    end
    
    def unknown_activecode!
      error! "UnKnown Active Code", 438
    end
    
    def attribute_error!
      error! "attributeerror: can't set attribute",439
    end
    
    def shortpwd_error!
      error! "password to short",439
    end
    
    def server_error!
      error! "Internal Server Error", 500
    end

    
    def is_email?(login)
        if login =~ /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
          true
        else
          false
        end 
    end

    def get_token
      loop do
        token = Devise.friendly_token
        unless User.where(authentication_token: token).first
        break token
        end
      end
    end

    def warden
      env['warden'].params[:single_access_token] = env["HTTP_ACCESSTOKEN"]
      env['warden']
    end

    def current_user
      @current_user ||= env["HTTP_ACCESSTOKEN"].nil? ? nil : User.find_by(:authentication_token => env["HTTP_ACCESSTOKEN"])
    end

    def authenticate!
      unless current_user
        Rails.logger.debug "authenticate fail with HTTP_ACCESSTOKEN #{env['HTTP_ACCESSTOKEN']} "
        token_expired!
      end
    end

    def http_get(url,params = {})
      uri = URI(url)
      uri.query = URI.encode_www_form(params)
      res = Net::HTTP.get_response(uri)

      res.body
    end

    def http_put(url,params = {})
      uri = URI.parse(url)
      res = Net::HTTP::Put.new(uri.path, initheader = {'Content-Type' =>'application/json'})
      res.body = params.to_json
      response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(res) }
      response.body
    end

    def http_post(url,params = {})
      url = URI.parse(url)
      req = Net::HTTP::Post.new(url.path,{'Content-Type' => 'application/json'})
      req.body = params.to_json
      res = Net::HTTP.new(url.host,url.port).start{|http| http.request(req)}
      
      res.body
    end

    def printL(data)
      Rails.logger.info  "=========================="
      Rails.logger.info "#{data}"
      Rails.logger.info  "=========================="
    end
  end
end
